<template>
	<div>
        <div class="toolBarStyle">
        <ButtonGroup v-for="(item,index) in buttonGroup" :key="index">
            <Button @click="cliclEvents(item.func)" :icon="item.Icon" type="primary">{{item.label}}</Button>
        </ButtonGroup>
        </div>
		 <Table border :columns="tableHead" :data="tableBody" :highlight-row="true" @on-row-click="getIndex" @on-row-dblclick="doubleEdit"></Table>
         <Page :total="total" show-elevator class="page_style" @on-change="getPage"></Page>
        <Modal v-model="openModal" title="新增项目" :mask-closable="false" :scrollable="true" width="70%" >
            <span slot="close">
                <Icon type="ios-close-empty" @click.native="closeModal('formList')"></Icon>
            </span> 
        	<Form :model="formList" :label-width="80" label-position="left" :rules="rulesList" ref="formList">
                <Row>
                    <Col span="11">
                		<FormItem label="项目名称" prop="works" required>
                			<Input v-model="formList.works"></Input>
                		</FormItem>
                    </Col>
                    <Col span="12" offset="1">
                		<FormItem label="发布时间" prop="end_time" required>
                			 <DatePicker type="date" placeholder="选择日期" v-model="formList.end_time" style="width:100%"></DatePicker>
                		</FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="11">
                		<FormItem label="参与人员" prop="members" required>
                			<Select v-model="arrayMembers" multiple>
                				<Option v-for="(item,index) in projectsMembers" :label="item.label" :value="item.value" :key="index"></Option>
                			</Select>
                		</FormItem>
                    </Col>
                    <Col span="12" offset="1">
                		<FormItem label="链接" prop="url" required>
                			<Input v-model="formList.url" ></Input>
                		</FormItem>
                    </Col>
            </Row>
        		<FormItem label="作品介绍" prop="introduction" required>
                    <quill-editor v-model="formList.introduction" id="imgStyle" :options="editorOption" ref="myQuillEditor" @change="onEditorChange($event)"></quill-editor>
                    <div class="limit" v-if="judge">当前已输入 <span>{{nowLength}}</span> 个字符</div>
                    <div class="limit" v-else>当前已输入 <span>{{nowLength}}</span> 个字符，您已经超出<span>{{needLength}}</span>个字符</div>
                </FormItem>
        	</Form> 
        	<div slot="footer">
                <Button @click="closeModal('formList')">取消</Button>
                <Button type="primary" @click="submit('formList')">确定</Button>
            </div> 
        </Modal>
	</div>
</template>
<script>
import {postDataToServer} from '../../assets/js/post.js'
import * as Quill from 'quill' //引入编辑器
    export default {
        data () {
        	const judgeUrl = (rules,value,callback) =>{
        		if(!value){
        			return callback(new Error('不能为空'));
        		}
        		else{
                    setTimeout(()=>{
                        if(this.isVaildUrl(value)){
                            callback();
                        }
                        else{
                            return callback(new Error('请输入正确的url'));
                        }
                    },1000);
        		}
        	};
            const judgeMember = (rules,value,callback)=>{
               if(this.arrayMembers.length==0) //如果是新增状态且数组为0
               {
                return callback(new Error('请至少选择一个成员'));
               }
               else{
                callback();
               }
            }
            return { 
            	openModal:false,
                maxlength:500,
                judge:true,//字符判断
                correct:false,//判断新增编辑
                arrayMembers:[],
                tableNumber:-1,
                total:0,
                editorOption:{
                    modules:{
                        toolbar:[
                            [{'size':['small',false,'large','huge']}],//字体大小
                            ['bold','italic'],//加粗，斜体
                            [{ 'header': '1' }],//H1
                            [{ 'header': '2' }],//H2
                            [{ 'color': [] }], //字体颜色
                            [{ 'font': [] }],//字体样式
                            [{ list: 'ordered' }, { list: 'bullet' }],//列表1，列表.
                            [{ 'align':[false,'center','right']}],//文本格式
                            ['image'],//上传图片
                            ['code-block'],//代码格式
                            ['clean'],//清除格式
                        ]
                    },
                    placeholder: '请输入50-500个字符',
                },
                nowLength:0,
                needLength:0,
            	formList:{
            		works:"",
                    members:"",
            		end_time:"",
            		url:"",
                    introduction:"",
            	},
            	rulesList:{
            		works:[
            		{required :true, message: '项目名称不能为空',trigger:'blur'},
            		{type:'string',max: 10, message: '名称不能多于10个字', trigger: 'blur' }
            		],
            		end_time:[
            		{ required: true, type: 'date', message: '请选择日期', trigger: 'change' }
            		],
            		members:[
            		 {validator : judgeMember,trigger:'change'},
            		],
            		url:[
            		{validator : judgeUrl, trigger :'blur'}
            		],
            		introduction:[
            		{ required: true, message: '请输入项目介绍', trigger: 'blur' },
                    { type: 'string', min: 50, message: '作品介绍不能少于50字', trigger: 'blur' },
                    {type:'string',max:500,message:'作品介绍不能多于500字',trigger:'blur'},
            		]
            	},
                tableHead: [
                    {
                        title: '项目名称',
                        key: 'works',
                        align:"center"
                    },
                    {
                        title: '发布时间',
                        key: 'end_time',
                        align:'center'
                    },
                    {
                        title: '参与人员',
                        key: 'members',
                        align:"center",
                        ellipsis:'true',
                    },                   
                    {
                    	title:'链接',
                    	key:'url',
                    	align:'center',
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width: 200,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.show(params.index)
                                        }
                                    }
                                }, '查看'),
                                h('Button',{
                                	props:{
                                		type:'primary',
                                		size:'small',
                                	},
                                	style:{
                                		marginRight :'5px'
                                	},
                                	on:{
                                		click: () => {
                                			this.edit(params.index);
                                		}
                                	}
                                },'修改'),
                                h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: () => {
                                            this.remove(params.index)
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                tableBody: [],
                projectsMembers:[{
                    label:"罗淦",
                    value:"罗淦",
                },{
                    label:"张耕博",
                    value:"张gay",
                }],
                buttonGroup:[{
                    label:"新增",
                    func:"addRow",
                    Icon:"plus-round",
                },
                {
                    label:"编辑",
                    func:"edit",
                    Icon:"edit",
                },{
                    label:"删除",
                    func:"remove",
                    Icon:"android-close",
                },{
                    label:"查看所有数据",
                    func:"update",
                    Icon:"ios-undo",
                }
                ]
            }             
        },
        created(){
            this.getInfo(false);
        },
         mounted() {
        },
        methods: {
             getInfo(page){
                if(!page)
                    page = 1;
                let postData = {};
                let parameter = new Object();
                postData.url = "PROJECT_LISTPAGE";
                parameter.page_no = page;
                postData.parameter = parameter;
                postDataToServer(postData).then((data)=>{
                    this.tableBody = data.data.rows;
                    this.total = data.data.count;
                });
            },
            show (index) {
                this.$Modal.info({
                    title: '项目信息',
                    content: `项目名称：${this.tableBody[index].works}<br>发布时间：${this.tableBody[index].end_time}<br>参与人员：${this.tableBody[index].members}<br>链接：${this.tableBody[index].url}`
                })
            },
            edit(index){
                if(index!=-1){
                    this.correct = true;
                    this.arrayMembers = this.tableBody[index].members.split(',');
                    for(var o in this.formList)
                        this.formList[o] = this.tableBody[index][o];
                    this.formList.id = this.tableBody[index].id;
                    this.openModal = true;
                }
                else
                    this.$Message.error("请选中数据");
            },
            remove (index) {
                if(index!=-1){
                    let postData = {};
                    let parameter = new Object();
                    postData.url = 'PROJECT_DEL';
                    parameter.id = this.tableBody[index].id;
                    postData.parameter = parameter;
                    postDataToServer(postData).then((data)=>{
                        if(data.message==="success")
                            this.$Message.success("删除成功");
                        else
                            this.$Message.error("删除失败");
                    });
                    this.getInfo(false);
                }
                else
                    this.$Message.error("请选中数据");
            },
            addRow(){
                this.correct = false;
            	this.openModal = true;
            },
            isVaildUrl(url){
            	// var urlRegExp=/^((https|http|ftp|rtsp|mms)?:\/\/)+[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/;
            	var Expression="^((https|http|ftp|rtsp|mms)?://)"      
            		+ "?(([0-9a-zA-Z_!~*'().&=+$%-]+: )?[0-9a-zA-Z_!~*'().&=+$%-]+@)?" //ftp的user@     
            		+ "(([0-9]{1,3}\\.){3}[0-9]{1,3}"                                 // IP形式的URL- 199.194.52.184     
            		+ "|"                                                         // 允许IP和DOMAIN（域名）     
            		+ "([0-9a-zA-Z_!~*'()-]+\\.)*"                                 // 域名- www.     
            		+ "([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\\."                     // 二级域名     
           			+ "[a-zA-Z]{2,6})"                                         // first level domain- .com or .museum     
            		+ "(:[0-9]{1,4})?"                                                     // 端口- :80     
            		+ "((/?)|"      
            		+ "(/[0-9a-zA-Z_!~*'().;?:@&=+$,%#-]+)+/?)$"; 
            var objExp=new RegExp(Expression);
    			if(objExp.test(url)){
        			return true;
    			}else{
        			return false;
    			}
            },
            submit(name){
                if(this.nowLength>=this.maxlength)
                    this.judge = false;
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.formList.members = this.arrayMembers.join(",");
                        let postData = {};
                        let parameter = new Object();
                        if(this.correct)
                            postData.url = "PROJECT_UPDATE";
                        else
                            postData.url = "PROJECT_ADD";
                        parameter = this.formList;
                        postData.parameter = parameter;
                        postDataToServer(postData).then((data)=>{
                            if(data.message==="success")
                                this.$Message.success('提交成功!');
                            else
                                this.$Message.error('提交失败!');
                            this.getInfo(false);
                        });
                        this.arrayMembers = [];
                        this.$refs[name].resetFields();
                        this.openModal = false;
                    } else {
                        this.$Message.error('表单验证失败!');
                    }
                });
            },
            closeModal(name){
                this.arrayMembers = [];
                this.$refs[name].resetFields();
                this.openModal = false;
            },
            onEditorChange({ editor, html, text }) {
                this.nowLength = text.length-1;
                this.needLength = this.nowLength - this.maxlength;
                if(this.needLength ==0){
                    this.judge = true;
                }
            },
            getIndex(row,index){
                this.tableNumber = index;
            },
            doubleEdit(row,index){
                this.edit(index);
            },
            cliclEvents(value)
            {
                switch(value){
                    case "addRow" : this.addRow(); break;
                    case "edit" : this.edit(this.tableNumber); break;
                    case "remove" : this.remove(this.tableNumber);break;
                    case "update" : this.getInfo(false);break;
                }
            },
            getPage(page){
                this.getInfo(page);
            }
        },
    }
</script>
<style type="text/css" scoped>
.toolBarStyle{
   background-color: #2d8cf0;
}
.limit {
  height: 30px;
  border: 1px solid #ccc;
  line-height: 30px;
  text-align: right; 
  span {
    color: #ee2a7b;
  }
}
.page_style{
    float: right; 
    margin-top:20px;
    margin-right: 20px; 
  }
</style>